package com.microservice.wechat.controller;

import com.microservice.api.common.Result;
import com.microservice.wechat.service.ArticleViewSyncService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 文章阅读量同步控制器
 * 提供手动触发同步的接口
 */
@Slf4j
@RestController
@RequestMapping("/article/sync")
public class ArticleViewSyncController {

    @Autowired
    private ArticleViewSyncService articleViewSyncService;

    /**
     * 手动触发文章阅读量同步
     * 
     * @return 执行结果
     */
    @PostMapping("/manual")
    public Result<String> manualSync() {
        log.info("收到手动同步请求");
        
        try {
            // 异步执行，避免接口超时
            new Thread(() -> {
                try {
                    articleViewSyncService.syncAllArticles();
                } catch (Exception e) {
                    log.error("手动同步执行异常", e);
                }
            }).start();
            
            return Result.success("同步任务已启动，请查看日志了解执行情况");
        } catch (Exception e) {
            log.error("启动同步任务失败", e);
            return Result.error("启动同步任务失败: " + e.getMessage());
        }
    }
}
